<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
             label-width="120px">
      <!--      <el-form-item label="机器id" prop="machineId">
              <el-input v-model="dataForm.machineId" placeholder="机器id"></el-input>
            </el-form-item>
            <el-form-item label="机器名称" prop="machineName">
              <el-input v-model="dataForm.machineName" placeholder="机器名称"></el-input>
            </el-form-item>-->
      <el-form-item v-if="dataForm.type" prop="projectId" label="项目">
        <el-select v-model="dataForm.projectId" placeholder="项目配置">
          <el-option v-for="obj in projectList" :key="obj.id" :label="obj.name" :value="obj.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-else prop="machineId" label="机器">
        <el-select v-model="dataForm.machineId" placeholder="机器配置" @change="changeMachine">
          <el-option v-for="obj in machineList" :key="obj.id" :label="obj.name"
                     :value="obj.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="dataForm.price" placeholder="价格"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="dataForm.note"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
/* eslint-disable prettier/prettier */
import {reactive, ref} from "vue";
import baseService from "@/service/baseService";
import {ElMessage} from "element-plus";

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const machineList = ref<any[]>([]);
const projectList = ref<any[]>([]);

const dataForm = reactive({
  id: "",
  projectId: "",
  machineId: "",
  machineName: "",
  price: "",
  note: "",

  type: ""
});

const validateMachine = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (!/\S/.test(value)) {
    return callback(new Error("必填项不能为空"));
  }
  if (!dataForm.id) {
    baseService.get("/yckj/projectmachine/list", {
      "projectId": dataForm.projectId,
      "machineId": dataForm.machineId
    }).then((res) => {
      if (res.data.length > 0) {
        return callback(new Error("当前机器已添加"));
      }
    });
  }
  callback();
};

const rules = ref({
  machineId: [{validator: validateMachine, trigger: "blur"}],
  price: [{required: true, message: '必填项不能为空', trigger: 'blur'}]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  if (dataForm.type) {
    Promise.all([getProjectList()]).then(() => {
      if (id) {
        getInfo(id);
      }
    });
  } else {

    Promise.all([getMachineList()]).then(() => {
      if (id) {
        getInfo(id);
      }
    });
  }
};

// 获取机器列表
const getMachineList = () => {
  return baseService.get("/yckj/machine/list").then((res) => {
    machineList.value = res.data;
  });
};

// 获取项目列表
const getProjectList = () => {
  return baseService.get("/yckj/project/list").then((res) => {
    projectList.value = res.data;
  });
};


// 获取信息
const getInfo = (id: number) => {
  baseService.get("/yckj/projectmachine/" + id).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

const changeMachine = (value: bigint) => {
  const selectedItem = machineList.value.find(item => item.id === value);
  dataForm.machineName = selectedItem.name;
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/yckj/projectmachine", dataForm).then((res) => {
      ElMessage.success({
        message: '成功',
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init,
  dataForm
});
</script>
